/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.common.web.Util;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hazardsource.util.Immutable;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.domain.ItemCheckRecord;
import com.koron.hiddendanger.mapper.CheckMapper;
import com.koron.hiddendanger.mapper.HiddenDangerMapper;
import com.koron.hiddendanger.service.api.HiddenDangerDiscoveryService;
import com.koron.hiddendanger.service.impl.HiddenDangerDiscoveryServiceImpl;
import com.koron.hiddendanger.service.impl.HiddenDangerRectificationServiceImpl;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.service.api.GridNodeService;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import com.koron.scene.domain.Device;
import com.koron.scene.domain.DeviceCheck;
import com.koron.scene.domain.DeviceCheckRelation;
import com.koron.scene.domain.DeviceHiddenDanger;
import com.koron.scene.mapper.DeviceCheckMapper;
import com.koron.scene.mapper.DeviceMapper;
import com.koron.scene.service.api.DeviceCheckService;
import com.koron.scene.utils.BusinessCode;
import com.koron.system.domain.DictData;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@PropertySource({"classpath:deviceCheckFlow.properties"})
public class DeviceCheckServiceImpl implements DeviceCheckService, AfterApprovalService, InitializingBean {

    private final static  Logger logger = LoggerFactory.getLogger(DeviceCheckServiceImpl.class);

    @Autowired
    private HiddenDangerDiscoveryService hiddenDangerService;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private GridNodeService nodeService;

    @Value("${device_check_confirmation}")
    private String flowTemplate;

    @Value("${flow.scene.setCode}")
    private String setCode;

    @Value("${risk_danger_setCode}")
    private String riskDangerSetCode;

    @Value("${danger_work_flow}")
    private String hiddenDangerWorkFlow;

    @Autowired
    private Util util;

    @Autowired
    private DictDataService dataService;

    @Override
    public DataBean<DeviceCheck> fetchDeviceChecks(String corpCode, String title, String checkEmployeeName, String executerName, Integer status, Integer start, Integer rows, String keyword) {
        if (logger.isDebugEnabled()) {
            logger.debug("checkEmployeeName = {}, executerName = {}, status = {}", checkEmployeeName, executerName, status);
        }
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCheckMapper mapper = factory.getMapper(DeviceCheckMapper.class);
            // 获取当前公司及下属公司信息
            String codes = util.getCodes(corpCode);
            List<DeviceCheck> deviceChecks = mapper.queryByCondition(codes, title, checkEmployeeName, executerName, status, start, rows, keyword);
            Integer total = mapper.countByCondition(codes, title, checkEmployeeName, executerName, status, keyword);
            if (deviceChecks != null && !deviceChecks.isEmpty()) {
                deviceChecks.forEach(dc -> {
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(dc.getCorpCode());
                    if (corpBean != null) {
                        dc.setCorpName(corpBean.getCorpName());
                    }
                });
            }
            DataBean<DeviceCheck> dataBean = new DataBean<>();
            dataBean.setList(deviceChecks);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(total);
            dataBean.setTotalPage(total > rows ? (total % rows == 0 ? total / rows : total / rows + 1) : 1);
            dataBean.setPageNo(start / rows + 1);
            return dataBean;
        }
    }

    @Override
    public DeviceCheck fetchOne(String id) {
        if (logger.isDebugEnabled()) {
            logger.debug("id = {}", id);
        }
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCheck deviceCheck = factory.getMapper(DeviceCheckMapper.class).queryOne(id);
            if (deviceCheck != null && StringUtils.isNotBlank(deviceCheck.getCorpCode())) {
                CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(deviceCheck.getCorpCode());
                if (corpBean != null) {
                    deviceCheck.setCorpName(corpBean.getCorpName());
                }
            }
            return deviceCheck;
        }
    }

    @Override
    public Boolean batchDetele(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(DeviceCheckMapper.class).batchDetele(idList) >= 0;
        }
    }

    @Override
    public Integer persist(DeviceCheck deviceCheck) {
        SessionFactory factory = null;
        try {
            Integer start = null, rows = null, status = null;
            String checkEmployeeName = null, executerName = null;
            DeviceCheck dest = null;
            factory = new SessionFactory();
            DeviceCheckMapper mapper = factory.getMapper(DeviceCheckMapper.class);
            List<DeviceCheck> checks = mapper.queryAllByCondition(deviceCheck.getCorpCode(), deviceCheck.getTitle(), checkEmployeeName, executerName, status, start, rows);
            if (checks != null && !checks.isEmpty()) {
                checks = checks.stream().filter(c -> c.getTitle().equals(deviceCheck.getTitle())).collect(Collectors.toList());
                dest = !checks.isEmpty() ? checks.get(0) : null;
            }

            if (StringUtils.isBlank(deviceCheck.getId())) {
                if (dest != null) {
                    factory.close(false);
                    return BusinessCode.CHECK_TITLE_DUP.getCode();
                }
                deviceCheck.setId(DefaultIdGenerator.getInstance().generateLongId());
                deviceCheck.setStatus(1);
                if (mapper.insert(deviceCheck) > 0) {
                    // 判断工作任务id 是否为空：如果不为空，则进行信息变更
                    if (StringUtils.isNotBlank(deviceCheck.getJobsTasksId())) {
                        JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                        JobsTasks jobsTasks = jobsTasksMapper.queryById(deviceCheck.getJobsTasksId());
                        if (jobsTasks == null) {
                            factory.close(false);
                            return BusinessCode.TASK_NOT_EXIST.getCode();
                        }
                        jobsTasks.setState(3);
                        jobsTasks.setBusinessId(deviceCheck.getId());
                        // 流程状态：0草稿 1审批中 2审批通过
                        jobsTasks.setFstatusflag(0);
                        if (jobsTasksMapper.completed(jobsTasks) != 1) {
                            factory.close(false);
                            return BusinessCode.EXCEPTION.getCode();
                        }
                    }
                    factory.close(true);
                    return BusinessCode.SUCCESS.getCode();
                }
            } else {
                DeviceCheck other = mapper.queryOne(deviceCheck.getId());
                deviceCheck.setStatus(other.getStatus());
                if (deviceCheck.getStatus() == 1) {
                    if (dest != null && !dest.getId().equals(deviceCheck.getId())) {
                        factory.close(false);
                        return BusinessCode.CHECK_TITLE_DUP.getCode();
                    }
                    if (mapper.update(deviceCheck) > 0) {
                        factory.close(true);
                        return BusinessCode.SUCCESS.getCode();
                    }
                }
                factory.close(false);
                return BusinessCode.CHECK_CANNOT_UPDATE.getCode();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        if (factory != null) {
            factory.close(false);
        }
        return BusinessCode.EXCEPTION.getCode();
    }


    @Override
    public Integer saveCheckDeviceRelation(StaffBean user, DeviceCheckRelation relation) {
        if (relation == null) {
            return BusinessCode.SUCCESS.getCode();
        }
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            List<String> attachmentList = new ArrayList<>();
            List<ItemCheckRecord> itemList = relation.getItemList();
            if (null != itemList && !itemList.isEmpty()) {
                for (ItemCheckRecord itemCheckRecord : itemList) {
                    itemCheckRecord.setId(DefaultIdGenerator.getInstance().generateLongId());
                    itemCheckRecord.setCheckRecordId(relation.getDeviceCheckRecordId());
                    itemCheckRecord.setChecklistEntryId(relation.getCheckListEntryId());
                }
            }
            List<DeviceHiddenDanger> hiddenDangers = relation.getHiddenDangers();
            if (hiddenDangers != null && !hiddenDangers.isEmpty()) {
                boolean f = true;
                for (int i = 0; i < hiddenDangers.size(); i++) {
                    DeviceHiddenDanger danger = hiddenDangers.get(i);
                    danger.setDerivation(4);
                    if (StringUtils.isNotBlank(danger.getId())) {
                        HiddenDangerDiscovery entity = hiddenDangerService.queryDangerOne(danger.getId()).getData();
                        if (null == entity || (entity.getState() != 0 && entity.getState() != 7)) {
                            removeAttachment(attachmentList);
                            factory.close(false);
                            return BusinessCode.HIDDENDANGER_CANNOT_EDIT.getCode();
                        }
                    }
                    List<String> newAtts = new ArrayList<>();
                    List<MultipartFile> files = danger.getFiles();
                    if (null != files && !files.isEmpty()) {
                        for (MultipartFile file : files) {
                            String url = clientWrapper.uploadFile(file);
                            newAtts.add(url + "#" + file.getOriginalFilename());
                        }
                    }
                    try {
                        f = process(factory, user, danger, newAtts, relation.getDeviceCheckRecordId());
                        attachmentList.addAll(newAtts);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                        f = false;
                    }
                    if (!f) {
                        //处理隐患失败即退出循环
                        break;
                    }
                }

                if (!f) {
                    removeAttachment(attachmentList);
                    factory.close(false);
                    return BusinessCode.EXCEPTION.getCode();
                }
                List<String> collect = hiddenDangers.stream().map(DeviceHiddenDanger::getId).collect(Collectors.toList());
                relation.setHiddenDangerIds(new Gson().toJson(collect));
            }
            DeviceMapper deviceMapper = factory.getMapper(DeviceMapper.class);
            DeviceCheckRelation other = deviceMapper.queryRelation(relation.getDeviceCheckRecordId(), relation.getDeviceId());
            if (other == null) {
                // 添加检查表详情信息
                if (null != itemList && itemList.size() > 0) {
                    deviceMapper.batchInsertCheckEntryItem(itemList);
                }
                deviceMapper.batchInsertRelation(new ArrayList() {{
                    add(relation);
                }});
            } else {
                // 根据检查记录id查找检查记录历史信息
                DeviceCheckRelation old = deviceMapper.queryRelation(relation.getDeviceCheckRecordId(), relation.getDeviceId());
                // 如原来选了检查表，修改时去掉后，获取原来的检查表id
                if (StringUtils.isEmpty(relation.getCheckListEntryId())) {
                    relation.setCheckListEntryId(old.getCheckListEntryId());
                }
                // 先删除检查表详情信息.在重新添加
                deviceMapper.deleteCheakEntryItem(relation.getDeviceCheckRecordId(), relation.getCheckListEntryId());
                if (null != itemList && itemList.size() > 0) {
                    deviceMapper.batchInsertCheckEntryItem(itemList);
                }
                deviceMapper.updateRelation(relation);
            }
            // 修改 设置台账 记录的检查日期
            if (factory.getMapper(DeviceMapper.class).updateLastCheckDateById(relation.getDeviceId(), new Date()) != 1) {
                factory.close(false);
                return BusinessCode.EXCEPTION.getCode();
            }
            factory.close(true);
            return BusinessCode.SUCCESS.getCode();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (factory != null) {
                factory.close(false);
            }
            return BusinessCode.EXCEPTION.getCode();
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }


    private void removeAttachment(List<String> attachmentList) {
        if (!attachmentList.isEmpty()) {
            for (String att : attachmentList) {
                try {
                    clientWrapper.deleteFile(att.split("#")[0]);
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
    }


    private boolean process(SessionFactory factory, StaffBean user, DeviceHiddenDanger dangerDiscovery, List<String> newAtts, String deviceCheckRecordId) throws Exception {
        dangerDiscovery.setCheckRecordId(deviceCheckRecordId);
        dangerDiscovery.setUpdateUser(user.getName());
        dangerDiscovery.setUpdateTime(new Date());
        dangerDiscovery.setSubmitterCode(user.getCode() + "_" + user.getUserid());
        MessageBean<?> corpMsg = util.corp(user.getCode());
        if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
            DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
            dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
            dangerDiscovery.setCheckUnitName(corp.getName());
        }
        if (StringUtils.isNotEmpty(dangerDiscovery.getInnerStaff())) {
            String[] arrays = dangerDiscovery.getInnerStaff().split("[,，]");
            dangerDiscovery.setInnerStaff(new Gson().toJson(Arrays.asList(arrays)));
        }
        if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererCode())) {
            String[] arrays = dangerDiscovery.getDiscovererCode().split("[,，]");
            dangerDiscovery.setDiscovererCode(new Gson().toJson(Arrays.asList(arrays)));
        }
        if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererDepartment())) {
            String[] arrays = dangerDiscovery.getDiscovererDepartment().split("[,，]");
            dangerDiscovery.setDiscovererDepartment(new Gson().toJson(Arrays.asList(arrays)));
        }
        //草稿
        dangerDiscovery.setState(7);
        IndicationItems itemsUnfinish = factory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
        if (StringUtils.isEmpty(dangerDiscovery.getId())) {
            dangerDiscovery.setId(DefaultIdGenerator.getInstance().generateLongId());
            dangerDiscovery.setCode(hiddenDangerService.generateCode(factory, dangerDiscovery));
            dangerDiscovery.setAddTime(dangerDiscovery.getUpdateTime());
            dangerDiscovery.setAddUser(dangerDiscovery.getUpdateUser());
            Port port = hiddenDangerService.getPort();
            List<DeptBean> departmentTreeBeanList = port.dept(user == null ? "1c6646fffe514a4c9539ba05fd3d92eb" : user.getCode()).getData();
            dangerDiscovery.setSubmitterDepartment(departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0 ? null : departmentTreeBeanList.get(0).getCode());
            if (null != newAtts && newAtts.size() > 0) {
                dangerDiscovery.setAttachment(new Gson().toJson(newAtts));
            }
            factory.getMapper(HiddenDangerMapper.class).insertDanger(dangerDiscovery);
            //构建隐患整改记录，填充整改人、整改期限、验证人、确认人、整改措施等信息
            HiddenDangerRectification rectification = new HiddenDangerRectification();
            rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
            rectification.setConfirmPerson(dangerDiscovery.getConfirmPerson());
            rectification.setConfirmPersonName(dangerDiscovery.getConfirmPersonName());
            rectification.setRectifier(dangerDiscovery.getRectifier());
            rectification.setRectifierName(dangerDiscovery.getRectifierName());
            rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(dangerDiscovery.getDangerManager().split("_")[0], null).getData();
            List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(dangerDiscovery.getDangerManager().split("_")[0]).getData();
            rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
            rectification.setUpdateUser(dangerDiscovery.getUpdateUser());
            rectification.setUpdateUserName(dangerDiscovery.getUpdateUserName());
            rectification.setAddUser(dangerDiscovery.getAddUser());
            rectification.setAddUserName(dangerDiscovery.getAddUserName());
            rectification.setAddTime(dangerDiscovery.getAddTime());
            rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
            rectification.setDeadline(dangerDiscovery.getDeadline());
            rectification.setSolution(dangerDiscovery.getSolution());
            rectification.setHiddenDangerId(dangerDiscovery.getId());
            rectification.setRectificationState(itemsUnfinish == null ? null : itemsUnfinish.getId());
            rectification.setDelayState(0);
            factory.getMapper(HiddenDangerMapper.class).insertRectification(rectification);
            return true;
        } else {
            List<String> keepAttsList = new ArrayList<>();
            keepAttsList.addAll(newAtts);
            if (StringUtils.isNotEmpty(dangerDiscovery.getKeepAtts())) {
                String[] keepAttsArray = dangerDiscovery.getKeepAtts().split("[;；]");
                keepAttsList.addAll(Arrays.asList(keepAttsArray));
            }
            if (keepAttsList.size() > 0) {
                dangerDiscovery.setAttachment(new Gson().toJson(keepAttsList));
            }
            if (factory.getMapper(HiddenDangerMapper.class).updateDanger(dangerDiscovery) > 0) {
                if (StringUtils.isNotEmpty(dangerDiscovery.getDelAtts())) {
                    String[] delAttsArray = dangerDiscovery.getDelAtts().split("[;；]");
                    for (String att : delAttsArray) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
                //判断是否填写了隐患整改信息
                List<HiddenDangerRectification> rectificationList = factory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                HiddenDangerRectification rectification = new HiddenDangerRectification();
                rectification.setConfirmPerson(dangerDiscovery.getConfirmPerson());
                rectification.setConfirmPersonName(dangerDiscovery.getConfirmPersonName());
                rectification.setRectifier(dangerDiscovery.getRectifier());
                rectification.setRectifierName(dangerDiscovery.getRectifierName());
                rectification.setReviewer(dangerDiscovery.getReviewer());
                rectification.setReviewerName(dangerDiscovery.getReviewerName());
                rectification.setUpdateUser(dangerDiscovery.getUpdateUser());
                rectification.setUpdateUserName(dangerDiscovery.getUpdateUserName());
                rectification.setAddUser(dangerDiscovery.getAddUser());
                rectification.setAddUserName(dangerDiscovery.getAddUserName());
                rectification.setAddTime(dangerDiscovery.getAddTime());
                rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                rectification.setDeadline(dangerDiscovery.getDeadline());
                rectification.setSolution(dangerDiscovery.getSolution());
                rectification.setHiddenDangerId(dangerDiscovery.getId());
                rectification.setRectificationState(itemsUnfinish == null ? null : itemsUnfinish.getId());
                rectification.setDelayState(0);
                if (null == rectificationList || rectificationList.size() <= 0) {
                    rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                    factory.getMapper(HiddenDangerMapper.class).insertRectification(rectification);
                    return true;
                } else {
                    rectification.setId(rectificationList.get(0).getId());
                    factory.getMapper(HiddenDangerMapper.class).updateRectification(rectification);
                    return true;
                }
            }
            return false;
        }
    }


    @Override
    public DataBean<Device> fetchDeviceInCheck(String corpCode, String checkEmployeeCode, String deviceCheckRecordId, Integer start, Integer rows, Integer searchTag) {
        DataBean<Device> dataBean = new DataBean<>();
        List<Device> devices = null;
        Integer total = 0;
        try (SessionFactory factory = new SessionFactory()) {
            // 组织架构
            MessageBean<?> orgTree = util.getOrgTree();
            List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) orgTree.getData();
            //数据字典
            Map<String, DictData> cacheMap = dataService.getCacheMap();
            DeviceCheck deviceCheck = factory.getMapper(DeviceCheckMapper.class).queryOne(deviceCheckRecordId);
            if (deviceCheck == null) {
                devices = Collections.EMPTY_LIST;
            } else {
                List<HiddenDangerDiscovery> dangers = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(deviceCheckRecordId, null, null);
                //查询检查责任人负责的所有设备
                devices = factory.getMapper(DeviceMapper.class).queryForCheckEmployee(corpCode, checkEmployeeCode, start, rows);
                //devices = factory.getMapper(DeviceMapper.class).queryDeviceInCheck(checkEmployeeCode, null, start, rows);
                for (Device device : devices) {
                    device.setNormal(null);
                    device.setHiddenDangerIds(null);
                    List<DepartmentTreeBean> collect = departmentTreeBeanList.stream().filter(departmentTreeBean -> device.getCorpCode().equals(departmentTreeBean.getDepartmentCode())).collect(Collectors.toList());
                    if (null != collect && collect.size() > 0) {
                        device.setCorpName(collect.get(0).getName());
                    }
                    if (StringUtils.isNotBlank(device.getDeviceTypeId())) {
                        DictData element = cacheMap.get(device.getDeviceTypeId());
                        device.setDeviceTypeName(element != null ? element.getDictLabel() : "");
                    }
                }
                total = factory.getMapper(DeviceMapper.class).countForCheckEmployee(corpCode, checkEmployeeCode);
                //total = factory.getMapper(DeviceMapper.class).countDeviceInCheck(checkEmployeeCode, null);
                //查询检查责任人的设备检查结果(即是否正常)
                List<Device> resultDevices = factory.getMapper(DeviceMapper.class).queryDeviceInCheck(checkEmployeeCode, deviceCheckRecordId, start, rows);
                if (!resultDevices.isEmpty()) {
                    for (Device rd : resultDevices) {
                        devices.stream().forEach(d -> {
                            if (d.getId().equals(rd.getId())) {
                                d.setNormal(rd.getNormal());
                                // 获取检查表数据
                                if (StringUtils.isNotEmpty(rd.getCheckListEntryId())) {
                                    d.setCheckListEntryId(rd.getCheckListEntryId());
                                    List<ItemCheckRecord> itemCheckRecordList = factory.getMapper(DeviceMapper.class).queryCheckListEntry(deviceCheckRecordId, rd.getCheckListEntryId());
                                    d.setItemList(itemCheckRecordList);
                                }
                                if (StringUtils.isNotBlank(rd.getHiddenDangerIds())) {
                                    List<String> idList = JSONObject.parseArray(rd.getHiddenDangerIds(), String.class);
                                    List<HiddenDangerDiscovery> deviceDangers = dangers.stream().filter(danger -> idList.contains(danger.getId())).collect(Collectors.toList());
                                    if (deviceDangers != null && !deviceDangers.isEmpty()) {
                                        deviceDangers.forEach(item -> hiddenDangerService.getNames(item));
                                    }
                                    d.setHiddenDangers(deviceDangers);
                                }
                            }
                        });
                    }
                }
            }
            if (null != searchTag && searchTag == 0) {
                devices = devices.stream().filter(bean -> null == bean.getNormal()).collect(Collectors.toList());
            } else if (null != searchTag && searchTag == 1) {
                devices = devices.stream().filter(bean -> null != bean.getNormal()).collect(Collectors.toList());
            }
            dataBean.setList(devices);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(total);
            if (rows != null) {
                dataBean.setTotalPage(total > rows ? (total % rows == 0 ? total / rows : total / rows + 1) : 1);
                dataBean.setPageNo(start / rows + 1);
            }
            return dataBean;
        }
    }


    @Override
    public Boolean uploadRecordAttachment(String deviceCheckRecordId, String delFileAddress, String keepFileAddress, MultipartFile[] files) {
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCheck deviceCheck = factory.getMapper(DeviceCheckMapper.class).queryOne(deviceCheckRecordId);
            if (deviceCheck == null) {
                return false;
            }
            List<String> newAtts = new ArrayList<>();
            if (files != null && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    newAtts.add(url + "#" + file.getOriginalFilename());
                }
            }

            if (StringUtils.isNotEmpty(delFileAddress)) {
                String[] delAttsArray = delFileAddress.split("[;；]");
                for (String att : delAttsArray) {
                    clientWrapper.deleteFile(att.split("#")[0]);
                }
            }

            if (StringUtils.isNotEmpty(keepFileAddress)) {
                String[] keepAttsArray = keepFileAddress.split("[;；]");
                newAtts.addAll(Arrays.asList(keepAttsArray));
            }
            String attachment = newAtts.isEmpty() ? "" : new Gson().toJson(newAtts);
            return factory.getMapper(DeviceCheckMapper.class).updateCheckAttachment(deviceCheckRecordId, attachment) > 0;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return false;
        }
    }


    @Override
    public List<String> getRecordAttachment(String deviceCheckRecordId) {
        try (SessionFactory factory = new SessionFactory()) {
            String ids = factory.getMapper(DeviceCheckMapper.class).queryCheckAttachment(deviceCheckRecordId);
            if (StringUtils.isNotBlank(ids)) {
                return JSONObject.parseArray(ids, String.class);
            }
            return null;
        }
    }


    @Override
    public boolean submit(StaffBean user, DeviceCheck deviceCheck) {
        SessionFactory factory = new SessionFactory();
        try {
            deviceCheck.setStatus(2);
            deviceCheck.setUpdateUser(user.getCode());
            deviceCheck.setUpdateTime(new Date());
            deviceCheck.setUpdateUserName(user.getName());
            factory.getMapper(DeviceCheckMapper.class).update(deviceCheck);
            List<HiddenDangerDiscovery> dangerDiscoveries = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(deviceCheck.getId(), null, null);
            //将检查过程中发现的隐患状态设置为7：处于检查会签中的隐患，无法编辑，无法提交，
            //检查流程审批通过之后设置为草稿状态，这时可以提交隐患流程
            if (null != dangerDiscoveries && !dangerDiscoveries.isEmpty()) {
                for (HiddenDangerDiscovery dangerDiscovery : dangerDiscoveries) {
                    dangerDiscovery.setState(7);
                }
                factory.getMapper(HiddenDangerMapper.class).batchUpdateDanger(dangerDiscoveries);
            }
            //构造Audit
            Audit audit = new Audit(deviceCheck.getTitle(), "设备检查记录-" + deviceCheck.getTitle(), user.getName(), new Date());
            audit.setFlowType(1);
            audit.setFlowName(Immutable.DEVICECHECK_RESULT_CONFIRM);
            audit.setOperation(1);
            audit.setTarget(DeviceCheckServiceImpl.class.getName());
            audit.setCorpCode(deviceCheck.getCorpCode());
            audit.setBusinessIds(deviceCheck.getId());
            audit.setInitiatorCode(user.getCode());
            audit.setState(1);
            audit.setSetCode(setCode);
            audit.setTemplateKey(flowTemplate);
            audit.setInitiatorAccount(user.getUserid());
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            Map<String, Object> businessMap = new HashMap<>();
            String managerUserid = "";
            if (StringUtils.isEmpty(managerUserid)) {
                List<StaffBean> staffBeans = (List<StaffBean>) util.staff(deviceCheck.getCheckEmployeeCode().split("_")[0], null).getData();
                managerUserid = staffBeans.get(0).getUserid();
            }
            businessMap.put("manager", managerUserid);
            if (StringUtils.isNotEmpty(deviceCheck.getExecuterCode())) {
                String[] excuterCodes = deviceCheck.getExecuterCode().split("[,，]");
                StringBuilder codes = new StringBuilder();
                for (String code : excuterCodes) {
                    String userid = "";
                    if (StringUtils.isEmpty(userid)) {
                        List<StaffBean> staffBeans = (List<StaffBean>) util.staff(code.split("_")[0], null).getData();
                        userid = staffBeans.get(0).getUserid();
                    }
                    codes.append(userid).append(",");
                }
                businessMap.put("executors", codes.toString().substring(0, codes.lastIndexOf(",")));
            }

            if (StringUtils.isNotBlank(deviceCheck.getJobsTasksId())) {
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                JobsTasks jobsTasks = jobsTasksMapper.queryById(deviceCheck.getJobsTasksId());
                if (jobsTasks == null) {
                    factory.close(false);
                    return false;
                }
                // 任务状态：-1废弃，0待办，1完成，2延时完成，3执行中
                jobsTasks.setState(3);
                jobsTasks.setBusinessId(deviceCheck.getId());
                // 流程状态：0草稿 1审批中 2审批通过
                jobsTasks.setFstatusflag(1);
                if (jobsTasksMapper.completed(jobsTasks) != 1) {
                    factory.close(false);
                    return false;
                }
            }
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                return false;
            } else {
                factory.close();
                return true;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return false;
    }

    @Override
    public List<DeviceCheck> exportList(String corpCode, String title, String checkEmployeeName, String executerName, Integer status) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try (SessionFactory factory = new SessionFactory()) {
            String codes = util.getCodes(corpCode);
            List<DeviceCheck> deviceChecks = factory.getMapper(DeviceCheckMapper.class).queryByCondition(codes, title, checkEmployeeName, executerName, status, null, null, null);
            if (null != deviceChecks && !deviceChecks.isEmpty()) {
                deviceChecks.forEach(dc -> {
                    if (null != dc.getCheckTime()) {
                        dc.setCheckTimeStr(dateFormat.format(dc.getCheckTime()));
                    }
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(dc.getCorpCode());
                    if (corpBean != null) {
                        dc.setCorpName(corpBean.getCorpName());
                    }
                });
            }
            return deviceChecks;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public Device fetchOneDeviceInCheck(String corpCode, String checkEmployeeCode, String deviceCheckRecordId, String deviceId) {
        Device device = null;
        try (SessionFactory factory = new SessionFactory()) {
            // 组织架构
            MessageBean<?> orgTree = util.getOrgTree();
            List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) orgTree.getData();
            //数据字典
            Map<String, DictData> cacheMap = dataService.getCacheMap();
            DeviceCheck deviceCheck = factory.getMapper(DeviceCheckMapper.class).queryOne(deviceCheckRecordId);
            if (null != deviceCheck) {
                List<HiddenDangerDiscovery> dangers = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(deviceCheckRecordId, null, null);
                //查询检查责任人负责的设备
                device = factory.getMapper(DeviceMapper.class).queryOneCheckEmployee(corpCode, checkEmployeeCode, deviceId);
                if (null != device) {
                    device.setNormal(null);
                    device.setHiddenDangerIds(null);
                    Device finalDevice = device;
                    List<DepartmentTreeBean> collect = departmentTreeBeanList.stream().filter(departmentTreeBean -> finalDevice.getCorpCode().equals(departmentTreeBean.getDepartmentCode())).collect(Collectors.toList());
                    if (null != collect && collect.size() > 0) {
                        device.setCorpName(collect.get(0).getName());
                    }
                    if (StringUtils.isNotBlank(device.getDeviceTypeId())) {
                        DictData element = cacheMap.get(device.getDeviceTypeId());
                        device.setDeviceTypeName(element != null ? element.getDictLabel() : "");
                    }
                }
                //查询检查责任人的设备检查结果(即是否正常)
                List<Device> resultDevices = factory.getMapper(DeviceMapper.class).queryDeviceInCheck(checkEmployeeCode, deviceCheckRecordId, null, null);
                if (!resultDevices.isEmpty()) {
                    for (Device rd : resultDevices) {
                        if (null != device) {
                            if (device.getId().equals(rd.getId())) {
                                device.setNormal(rd.getNormal());
                                // 获取检查表数据
                                if (StringUtils.isNotEmpty(rd.getCheckListEntryId())) {
                                    device.setCheckListEntryId(rd.getCheckListEntryId());
                                    List<ItemCheckRecord> itemCheckRecordList = factory.getMapper(DeviceMapper.class).queryCheckListEntry(deviceCheckRecordId, rd.getCheckListEntryId());
                                    device.setItemList(itemCheckRecordList);
                                }
                                if (StringUtils.isNotBlank(rd.getHiddenDangerIds())) {
                                    List<String> idList = JSONObject.parseArray(rd.getHiddenDangerIds(), String.class);
                                    List<HiddenDangerDiscovery> deviceDangers = dangers.stream().filter(danger -> idList.contains(danger.getId())).collect(Collectors.toList());
                                    if (deviceDangers != null && !deviceDangers.isEmpty()) {
                                        deviceDangers.forEach(item -> hiddenDangerService.getNames(item));
                                    }
                                    device.setHiddenDangers(deviceDangers);
                                }
                            }
                        }
                    }
                }
            }
        }
        return device;
    }

    @Override
    public MessageBean queryOneDeviceOfDanger(String corpCode, String deviceCheckRecordId, String deviceId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = new MessageBean<>();
        DataBean dataBean = new DataBean();
        List<HiddenDangerDiscovery> deviceDangers = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            DeviceCheck deviceCheck = factory.getMapper(DeviceCheckMapper.class).queryOne(deviceCheckRecordId);
            if (null != deviceCheck) {
                // 获取设备检查记录
                DeviceCheckRelation deviceCheckRelation = factory.getMapper(DeviceMapper.class).queryRelation(deviceCheckRecordId, deviceId);
                if (null != deviceCheckRelation) {
                    String hiddenDangerIds = deviceCheckRelation.getHiddenDangerIds();
                    List<String> list = JSONObject.parseArray(hiddenDangerIds, String.class);
                    if (null != list && list.size() > 0) {
                        deviceDangers = factory.getMapper(HiddenDangerMapper.class).queryDangerByIdList(list);
                        if (deviceDangers != null && !deviceDangers.isEmpty()) {
                            deviceDangers.forEach(item -> hiddenDangerService.getNames(item));
                        }
                    }
                }
            }
        }
        Integer total = deviceDangers.size();
        dataBean.setTotalNumber(total);
        dataBean.setPageNo(page);
        dataBean.setPageSize(pageSize);
        dataBean.setTotalPage(total > pageSize ? (total % pageSize == 0 ? total / pageSize : total / pageSize + 1) : 1);
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
                start = (page <= 1) ? 0 : (page - 1) * pageSize;
                end = page * pageSize;
            }
            if (start != null && end != null) { //需要分页
                if (end > total) {
                    end = total;
                    if (start > end) {
                        start = end;
                    }
                }
            }
        }
        dataBean.setList(deviceDangers.subList(start, end));
        msg.setData(dataBean);
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        return msg;
    }

    @Override
    public MessageBean<?> saveCheckDanger(StaffBean user, String deviceCheckRecordId, String deviceId, HiddenDangerDiscovery dangerDiscovery, String delFileAddress, String keepFileAddress, MultipartFile[] files) {
        MessageBean<Integer> msg = new MessageBean<>();
        List<String> newAtts = new ArrayList<>();
        SessionFactory factory = null;
        try {
            DeviceCheckRelation relation = new DeviceCheckRelation();
            if (StringUtils.isEmpty(deviceId)) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("设备id不能为空");
                return msg;
            }
            relation.setDeviceId(deviceId);
            if (StringUtils.isEmpty(deviceCheckRecordId) && StringUtils.isEmpty(dangerDiscovery.getCheckRecordId())) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("设备检查记录id不能为空");
                return msg;
            }
            deviceCheckRecordId = StringUtils.isEmpty(deviceCheckRecordId) ? dangerDiscovery.getCheckRecordId() : deviceCheckRecordId;
            relation.setDeviceCheckRecordId(deviceCheckRecordId);
            factory = new SessionFactory();
            if (null != dangerDiscovery) {
                dangerDiscovery.setCheckRecordId(deviceCheckRecordId);
                dangerDiscovery.setUpdateUser(user.getName());
                dangerDiscovery.setUpdateTime(new Date());
                dangerDiscovery.setSubmitterCode(user.getCode() + "_" + user.getUserid());
                if (StringUtils.isNotEmpty(dangerDiscovery.getInnerStaff())) {
                    String[] arrays = dangerDiscovery.getInnerStaff().split("[,，]");
                    List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
                    dangerDiscovery.setInnerStaff(new Gson().toJson(collect));
                }
                if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererCode())) {
                    String[] arrays = dangerDiscovery.getDiscovererCode().split("[,，]");
                    List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
                    dangerDiscovery.setDiscovererCode(new Gson().toJson(collect));
                }
                if (StringUtils.isNotEmpty(dangerDiscovery.getDiscovererDepartment())) {
                    String[] arrays = dangerDiscovery.getDiscovererDepartment().split("[,，]");
                    List<String> collect = Arrays.asList(arrays).stream().filter(str -> StringUtils.isNotEmpty(str)).collect(Collectors.toList());
                    dangerDiscovery.setDiscovererDepartment(new Gson().toJson(collect));
                }
                if (StringUtils.isEmpty(dangerDiscovery.getCorpCode())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_CORPCODE.getCode());
                    msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_CORPCODE.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getGridCode())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_GRIDCODE.getCode());
                    msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_GRIDCODE.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDescription())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getElementFristType())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("一级分类不能为空");
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getElementSecondType())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("二级分类不能为空");
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDangerType())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("排序不能为空");
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDangerLevel())) {
                    msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription("隐患分级不能为空");
                    return msg;
                }
                if (null != files && files.length > 0) {
                    for (MultipartFile file : files) {
                        String fileName = file.getOriginalFilename();
                        //获取文件后缀名
                        String substring = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                        //判断是否属于图片
                        boolean contains = Lists.newArrayList("bmp", "gif", "jpg", "psd", "tiff", "eps", "tga", "jpeg", "png").contains(substring);
                        if (!contains) {
                            msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.FAILURE.getCode());
                            msg.setDescription(fileName + "不是图片，请上传图片");
                            return msg;
                        }
                        String url = clientWrapper.uploadFile(file);
                        newAtts.add(url + "#" + file.getOriginalFilename());
                    }
                }
                if (StringUtils.isNotEmpty(dangerDiscovery.getCheckRecordId())) {
                    Map deviceCheck = factory.getMapper(CheckMapper.class).queryDeviceCheck(dangerDiscovery.getCheckRecordId());
                    if (null != deviceCheck && !deviceCheck.isEmpty() && "1".equals(deviceCheck.get("status").toString())) {
                        dangerDiscovery.setState(7);
                    } else {
                        dangerDiscovery.setState(0);
                    }
                }
                if (StringUtils.isEmpty(dangerDiscovery.getId())) {
                    // 新增
                    dangerDiscovery.setId(DefaultIdGenerator.getInstance().generateLongId());
                    dangerDiscovery.setCode(generateCode(factory, dangerDiscovery));
                    dangerDiscovery.setAddTime(dangerDiscovery.getUpdateTime());
                    dangerDiscovery.setAddUser(dangerDiscovery.getUpdateUser());
                    if (StringUtils.isBlank(dangerDiscovery.getCheckRecordId()) && StringUtils.isBlank(dangerDiscovery.getFreeSnapId())) {
                        dangerDiscovery.setDerivation(4);
                    }
                    MessageBean<?> corpMsg = util.corp(user.getCode());
                    if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                        DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                        dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                        dangerDiscovery.setCheckUnitName(corp.getName());
                    }
                    if (null != newAtts && newAtts.size() > 0) {
                        dangerDiscovery.setAttachment(new Gson().toJson(newAtts));
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getDeviceCode())) {
                        dangerDiscovery.setDeviceCode("LSHDD-" + dangerDiscovery.getId().substring(dangerDiscovery.getId().length() - 6));
                    }
                    List<DeptBean> departmentTreeBeanList = (List<DeptBean>) util.dept(user.getCode()).getData();
                    dangerDiscovery.setSubmitterDepartment(departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0 ? null : departmentTreeBeanList.get(0).getCode());

                    factory.getMapper(HiddenDangerMapper.class).insertDanger(dangerDiscovery);
                } else {
                    //修改
                    //先判断是否已经提交过了
                    HiddenDangerDiscovery entity = factory.getMapper(HiddenDangerMapper.class).queryDangerOne(dangerDiscovery.getId());
                    if (null == entity) {
                        msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_NOT_EXISIT.getCode());
                        msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_NOT_EXISIT.getDescription());
                        return msg;
                    }
                    if (entity.getState() != 0 && entity.getState() != 7) {
                        msg.setCode(com.koron.hiddendanger.uitls.BusinessCode.DANGER_IS_COMMITED.getCode());
                        msg.setDescription(com.koron.hiddendanger.uitls.BusinessCode.DANGER_IS_COMMITED.getDescription());
                        return msg;
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getCheckUnit()) && StringUtils.isEmpty(dangerDiscovery.getCheckUnitName())) {
                        if (StringUtils.isEmpty(entity.getCheckUnit()) && StringUtils.isEmpty(entity.getCheckUnitName())) {
                            MessageBean<?> corpMsg = util.corp(user.getCode());
                            if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                                DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                                dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                                dangerDiscovery.setCheckUnitName(corp.getName());
                            }
                        } else {
                            dangerDiscovery.setCheckUnit(entity.getCheckUnit());
                            dangerDiscovery.setCheckUnitName(entity.getCheckUnitName());
                        }
                    }
                    List<String> keepAttsList = new ArrayList<>();
                    if (null != newAtts && newAtts.size() > 0) {
                        keepAttsList.addAll(newAtts);
                    }
                    if (StringUtils.isNotEmpty(keepFileAddress)) {
                        String[] keepArray = keepFileAddress.split("[;；]");
                        newAtts.addAll(Arrays.asList(keepArray));
                    }
                    if (null != keepAttsList && keepAttsList.size() > 0) {
                        dangerDiscovery.setAttachment(new Gson().toJson(keepAttsList));
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getDeviceCode())) {
                        dangerDiscovery.setDeviceCode("LSHDD-" + dangerDiscovery.getId().substring(dangerDiscovery.getId().length() - 8));
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getLegalBasis()) || ("null").equals(dangerDiscovery.getLegalBasis())) {
                        dangerDiscovery.setLegalBasis("");
                    }
                    if (StringUtils.isEmpty(dangerDiscovery.getLocation()) || ("null").equals(dangerDiscovery.getLocation())) {
                        dangerDiscovery.setLocation("");
                    }
                    Integer value = factory.getMapper(HiddenDangerMapper.class).updateDanger(dangerDiscovery);
                    if (value > 0) {
                        if (StringUtils.isNotEmpty(delFileAddress)) {
                            String[] delAttsArray = delFileAddress.split("[，,]");
                            for (String att : delAttsArray) {
                                clientWrapper.deleteFile(att.split("#")[0]);
                            }
                        }
                    }
                }
            }
            DeviceMapper deviceMapper = factory.getMapper(DeviceMapper.class);
            DeviceCheckRelation other = deviceMapper.queryRelation(deviceCheckRecordId, deviceId);
            if (other == null) {
                relation.setNormal(false);
                List<String> collect = Arrays.asList(dangerDiscovery.getId());
                relation.setHiddenDangerIds(new Gson().toJson(collect));
                deviceMapper.batchInsertRelation(new ArrayList() {{
                    add(relation);
                }});
            } else {
                // 根据检查记录id查找检查记录历史信息
                String hiddenDangerIds = other.getHiddenDangerIds();
                List<String> list = JSONObject.parseArray(hiddenDangerIds, String.class);
                if (null == list) {
                    list = new ArrayList<>();
                }
                list.add(dangerDiscovery.getId());
                other.setHiddenDangerIds(new Gson().toJson(list));
                deviceMapper.updateRelation(other);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            return MessageBean.create(BusinessCode.FAILURE.getCode(), BusinessCode.FAILURE.getDescription(), void.class);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }


    public String generateCode(SessionFactory factory, HiddenDangerDiscovery dangerDiscovery) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
        Integer counter = factory.getMapper(HiddenDangerMapper.class).countCode(date.substring(2, 4));
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(4); // 设置最大整数位数
        nf.setMinimumIntegerDigits(4); // 设置最小整数位数
        StringBuilder sb = new StringBuilder();
        sb.append("YD").append(date.substring(2, 4)).append(nf.format(counter));
        return sb.toString();
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            DeviceCheck deviceCheck = factory.getMapper(DeviceCheckMapper.class).queryOne(audit.getBusinessIds());
            deviceCheck.setStatus(3);
            factory.getMapper(DeviceCheckMapper.class).update(deviceCheck);
            if (StringUtils.isNotBlank(deviceCheck.getJobsTasksId())) {
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                JobsTasks jobsTasks = jobsTasksMapper.queryById(deviceCheck.getJobsTasksId());
                if (jobsTasks == null) {
                    factory.close(false);
                    return;
                }
                // 完成日期
                Date completedTime = new Date();
                // 任务状态：-1废弃，0待办，1完成，2延时完成，3执行中
                if (jobsTasks.getEndTime() == null || jobsTasks.getEndTime().after(completedTime)) {
                    jobsTasks.setState(1);
                } else {
                    jobsTasks.setState(2);
                }
                jobsTasks.setCompletedTime(completedTime);
                jobsTasks.setBusinessId(deviceCheck.getId());
                // 流程状态：0草稿 1审批中 2审批通过
                jobsTasks.setFstatusflag(2);
                if (jobsTasksMapper.completed(jobsTasks) != 1) {
                    factory.close(false);
                    return;
                }
            }

            //审批通过，将检查记录中的隐患修改为草稿状态，便于可以启动隐患流程
//
//            List<HiddenDangerDiscovery> dangers = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(audit.getBusinessIds(),
//                    null, null);
//            if (null != dangers && !dangers.isEmpty()) {
//                for (HiddenDangerDiscovery dangerDiscovery : dangers) {
//                    dangerDiscovery.setState(0);
//                }
//                factory.getMapper(HiddenDangerMapper.class).batchUpdateDanger(dangers);
//            }

            // 获取隐患数据
            List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(audit.getBusinessIds(), null, null);
            // 检查记录审批完成后，自动启动隐患整改流程
            if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                // 获取随手拍确认人
                String checkEmployeeCode = deviceCheck.getCheckEmployeeCode();
                List<StaffBean> staffBeans = (List<StaffBean>) util.staff(checkEmployeeCode.split("_")[0], null).getData();
                StaffBean user = staffBeans.get(0);
                // 获取隐患负责人
                Set<String> codeLists = dangerDiscoveryList.stream().map(bean -> bean.getDangerManager().split("_")[0]).collect(Collectors.toSet());
                List<String> noticeCodeList = new ArrayList<>();
                for (String code : codeLists) {
                    try (SessionFactory sessionFactory = new SessionFactory()) {
                        // 同一个隐患负责人，提交成一条隐患流程
                        List<HiddenDangerDiscovery> discoveryList = dangerDiscoveryList.stream().filter(bean -> code.equals(bean.getDangerManager().split("_")[0])).collect(Collectors.toList());
                        //整理隐患整改记录
                        HiddenDangerMapper mapper = sessionFactory.getMapper(HiddenDangerMapper.class);
                        List<HiddenDangerRectification> rectificationList = new ArrayList<>();
                        List<HiddenDangerRectification> deleteList = new ArrayList<>();
                        List<String> approvalList = new ArrayList<>();
                        for (HiddenDangerDiscovery dangerDiscovery : discoveryList) {
                            //查询提交的隐患是不是已经有了整改记录；
                            List<HiddenDangerRectification> rectificationList1 = sessionFactory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                            //删除之前有的整改记录信息
                            if (rectificationList1 != null && rectificationList1.size() > 0) {
                                deleteList.addAll(rectificationList1);
                            }
                            //保存隐患整改信息，主要是配置隐患整改信息的验证人
                            HiddenDangerRectification rectification = new HiddenDangerRectification();
                            //保存整改信息
                            rectification.setHiddenDangerId(dangerDiscovery.getId());
                            rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                            rectification.setAddTime(dangerDiscovery.getUpdateTime());
                            rectification.setAddUser(user.getName());
                            rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                            rectification.setUpdateUser(user.getName());
                            rectification.setRectifier(dangerDiscovery.getDangerManager());
                            rectification.setRectifierName(dangerDiscovery.getDangerManagerName());
                            rectification.setDeadline(dangerDiscovery.getRectificationPeriod());
                            rectification.setSolution(dangerDiscovery.getDescription());
                            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(dangerDiscovery.getDangerManager().split("_")[0], null).getData();
                            List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(dangerDiscovery.getDangerManager().split("_")[0]).getData();
                            if (!approvalList.contains(staffBeanList.get(0).getUserid())) {
                                approvalList.add(staffBeanList.get(0).getUserid());
                            }
                            rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
                            rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                            rectification.setDelayState(0);
                            IndicationItems items = sessionFactory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                            rectification.setRectificationState(items == null ? null : items.getId());
                            rectificationList.add(rectification);
                        }
                        //更新选中的隐患为确认状态；启动隐患流程
                        List<String> ids = discoveryList.stream().map(bean -> bean.getId()).collect(Collectors.toList());
                        mapper.updateDangerState(2, ids);
                        try {
                            for (HiddenDangerDiscovery discovery : discoveryList) {
                                List<Message> messages = new ArrayList<>();
                                if (discovery.getCopyPerson() != null) {
                                    String[] copyPersons = discovery.getCopyPerson().split(",");
                                    for (String copyPerson : copyPersons) {
                                        Message message = new Message();
                                        message.setId(DefaultIdGenerator.getInstance().generateLongId());
                                        message.setTitle("有一项您关注的隐患整改");
                                        message.setIsRead(0);
                                        message.setIsRemove(0);
                                        message.setAddTime(new Date());
                                        message.setAddUser(discovery.getAddUser());
                                        message.setContent("隐患描述：" + discovery.getDescription());
                                        message.setReceiverCode(copyPerson.split("_")[0]);
                                        messages.add(message);
                                    }
                                }
                                if (messages != null && messages.size() > 0) {
                                    factory.getMapper(MessageMapper.class).batchInsert(messages);
                                }
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage(),e);
                        }
                        mapper.batchInsertRectification(rectificationList);
                        if (deleteList != null && deleteList.size() > 0) {
                            List<String> deleteIdList = deleteList.stream().map(HiddenDangerRectification::getId).collect(Collectors.toList());
                            mapper.bateDeleteRectification(deleteIdList);
                        }
                        Date date = new Date();
                        Audit auditBean = new Audit();
                        auditBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                        auditBean.setUpdateUser(user.getName());
                        auditBean.setUpdateTime(date);
                        auditBean.setAddTime(date);
                        auditBean.setAddUser(user.getName());
                        auditBean.setFlowType(2);
                        auditBean.setOperation(1);
                        auditBean.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
                        auditBean.setFlowName(Immutable.HIDDENDANGER_WORKFLOW);
                        auditBean.setNowNodeCode("Process-task2");
                        auditBean.setTitle("隐患整改流程");
                        auditBean.setCorpCode(discoveryList.get(0).getCorpCode());
                        auditBean.setBusinessIds(new Gson().toJson(ids));
                        auditBean.setInitiatorCode(user.getCode());
                        auditBean.setTemplateKey(hiddenDangerWorkFlow);
                        auditBean.setInitiatorAccount(user.getUserid());
                        auditBean.setSetCode(riskDangerSetCode);
                        auditBean.setDescription("隐患整改流程");
                        auditBean.setState(1);
                        Map<String, Object> businessDataMap = new HashMap<>();
                        String userid = approvalList.stream().collect(Collectors.joining(","));
                        businessDataMap.put("rectifier", userid);
                        businessDataMap.put("reviewer", userid);
                        businessDataMap.put("verification", user.getUserid());
                        if (!flowManagement.initFlow(user, auditBean, businessDataMap)) {
                            // 如果自动提交隐患失败，将隐患修改为草稿，可在隐患台账处提交
                            factory.getMapper(HiddenDangerMapper.class).updateDangerState(0, ids);
                            sessionFactory.close(false);
                        } else {
                            // 提交成功，生成整改通知书
                            String noticeCode = HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationNotice(sessionFactory, user, discoveryList);
                            if (StringUtils.isNotEmpty(noticeCode)) {
                                noticeCodeList.add(noticeCode);
                            }
                            sessionFactory.close();
                        }
                    }
                }
            }

//            String manager = deviceCheck.getCheckEmployeeCode();
//            StaffBean user = (StaffBean) hiddenDangerService.getPort().staff(manager, null).getData().get(0);
//            //审批通过，将检查记录中的隐患启动相应的流程
//            List<HiddenDangerDiscovery> dangers = factory.getMapper(HiddenDangerMapper.class).queryDangerByCheckRecordId(audit.getBusinessIds(),
//                    null, null);
//            Date date = new Date();
//            if (null != dangers && !dangers.isEmpty()) {
//                for (HiddenDangerDiscovery dangerDiscovery : dangers) {
//                    /*Audit bean = new Audit("隐患待确认", dangerDiscovery.getDescription(), user.getName(), date);
//                    bean.setFlowType(2);
//                    bean.setFlowName(Immutable.CONMFIRM_HIDDENDANGER);
//                    bean.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
//                    bean.setOperation(1);
//                    bean.setCorpCode(dangerDiscovery.getCorpCode());
//                    bean.setBusinessIds(dangerDiscovery.getId());
//                    bean.setInitiatorCode(dangerDiscovery.getSubmitterCode());
//                    bean.setNextParticipantCode(dangerDiscovery.getGridCode());
//                    bean.setState(1);
//                    bean.setBusinessIds(dangerDiscovery.getId());
//                    bean.setTemplateKey(hiddenDangerConfirm);
//                    bean.setId(DefaultIdGenerator.getInstance().generateLongId());*/
//                    GridNode node = factory.getMapper(GridNodeMapper.class).queryByCode(dangerDiscovery.getGridCode());
//                    StringBuilder gridManager = new StringBuilder();
//                    if (null != node) {
//                        if (StringUtils.isEmpty(node.getBusinessStaffCode())) {
//                            if (StringUtils.isEmpty(node.getSafetyStaffCode())) {
//                                //去找离得最近的网格节点的相关人
//                                setGridManager(gridManager, dangerDiscovery.getGridCode(), audit);
//                            } else {
//                                gridManager.append(node.getSafetyStaffCode());
//                            }
//                        } else {
//                            gridManager.append(node.getBusinessStaffCode());
//                        }
//                    } else {
//                        DeptSafetyStaffBean deptSafetyStaffBean = factory.getMapper(GridNodeMapper.class).deptStaff(dangerDiscovery.getGridCode());
//                        if (null != deptSafetyStaffBean) {
//                            if (StringUtils.isEmpty(deptSafetyStaffBean.getBusinessStaffCode())) {
//                                if (StringUtils.isEmpty(deptSafetyStaffBean.getSafetyStaffCode())) {
//                                    //去找离得最近的网格节点的相关人
//                                    setGridManager(gridManager, dangerDiscovery.getGridCode(), audit);
//                                } else {
//
//                                    setGridManager(gridManager, dangerDiscovery.getGridCode(), audit);
//                                }
//                            } else {
//                                gridManager.append(deptSafetyStaffBean.getBusinessStaffCode());
//                            }
//                        } else {
//                            //去找离得最近的网格节点相关人
//                            setGridManager(gridManager, dangerDiscovery.getGridCode(), audit);
//                        }
//                    }
//                    Map<String, Object> businessDataMap = new HashMap<>();
//                    if (StringUtils.isEmpty(gridManager)){
//                        dangerDiscovery.setState(4);
//                    }else{
//                        dangerDiscovery.setState(1);
//                        businessDataMap.put("gridManager", gridManager);
//                        /*if (!flowManagement.initFlow(user, bean, businessDataMap)) {
//                            factory.close(false);
//                            return;
//                        }*/
//                    }
//                    factory.getMapper(HiddenDangerMapper.class).updateDanger(dangerDiscovery);
//                }
//            }
            factory.close(true);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            DeviceCheck deviceCheck = factory.getMapper(DeviceCheckMapper.class).queryOne(audit.getBusinessIds());
            deviceCheck.setStatus(1);
            factory.getMapper(DeviceCheckMapper.class).update(deviceCheck);
            if (StringUtils.isNotBlank(deviceCheck.getJobsTasksId())) {
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                JobsTasks jobsTasks = jobsTasksMapper.queryById(deviceCheck.getJobsTasksId());
                if (jobsTasks == null) {
                    factory.close(false);
                    return;
                }
                // 任务状态：-1废弃，0待办，1完成，2延时完成，3执行中
                jobsTasks.setState(0);
                jobsTasks.setBusinessId(deviceCheck.getId());
                // 流程状态：0草稿 1审批中 2审批通过
                //jobsTasks.setFstatusflag(0);
                if (jobsTasksMapper.completed(jobsTasks) != 1) {
                    factory.close(false);
                }
            }
            factory.close(true);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(DeviceCheckServiceImpl.class.getName(), this);
        //map.put(HiddenDangerDiscoveryServiceImpl.class.getName(), new HiddenDangerDiscoveryServiceImpl());
    }

    private void setGridManager(StringBuilder gridManager, String code, Audit audit) {
        Map<String, String> map = nodeService.gridStaff(code);
        if (null != map && !map.isEmpty()) {
            String safetyStaffCode = map.get("safetyStaffCode");
            String businessStaffCode = map.get("businessStaffCode");
            String gridCode = map.get("code");
            audit.setNextGridNode(gridCode);
            if (StringUtils.isNotEmpty(businessStaffCode)) {
                gridManager.append(businessStaffCode);
            } else {
                gridManager.append(safetyStaffCode);
            }
        }
    }


    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
